package tingshu.repository;

import lombok.SneakyThrows;
import tingshu.data_object.UserDO;
import tingshu.util.DBUtil;
import tingshu.util.Log;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * @author houdaiqin
 * @date 2022/07/09 15:20
 **/
public class UserRepo {
    @SneakyThrows
    public void insert(UserDO userDO) {
        String sql = "insert into users (username, password) values (?, ?)";
        try (Connection c = DBUtil.connection()) {
            try (PreparedStatement ps = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
                ps.setString(1, userDO.username);
                ps.setString(2, userDO.password);

                Log.println("执行 SQL: " + ps.toString());
                ps.executeUpdate();

                // 得到自增 id 作为 uid
                try (ResultSet rs = ps.getGeneratedKeys()) {
                    rs.next();
                    userDO.uid = rs.getInt(1);
                }
            }
        }
    }

    /**
     * 从数据库的用户表中通过username查找出用户的uid和password
     * @param username
     * @return
     */
    @SneakyThrows
    public UserDO selectOneByUsername(String username) {
        String sql = "select uid, username, password from users where username = ?";
        try (Connection c = DBUtil.connection()) {
            try (PreparedStatement ps = c.prepareStatement(sql)) {
                ps.setString(1, username);

                Log.println("执行 SQL: " + ps.toString());
                try (ResultSet rs = ps.executeQuery()) {
                    if (!rs.next()) {
                        return null;
                    }
                    //将数据封装到UserDO中返回给UserService
                    return new UserDO(
                            rs.getInt("uid"),
                            rs.getString("username"),
                            rs.getString("password")
                    );
                }
            }
        }
    }
}